package org.jeecg.modules.wechat;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.RedisUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.text.MessageFormat;
import java.util.*;


/**
 * 赛事水平
 *
 * @author chuloud
 * @email 80567375@qq.com
 * @date 2022-09-14 10:34:19
 */
//@Api(tags = "501小程序接口")
@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private ISysUserService userService;

    @Autowired
    private RedisUtil redisUtil;

    //小程序名称：nike activity  wx87b602e734bb8799   cdc812ef07a22755e1b7c89d9b96a525
    //小程序名称：chulture activity  wx121d5951e83771e4   4e619cbfe9a703063e4754475234e54a
    private String appid = "wx87b602e734bb8799";
    private String secret = "cdc812ef07a22755e1b7c89d9b96a525";

    @ApiOperation(value = "通过code获取openid", notes = "通过微信授权code获取用户openid")
    @GetMapping("/getOpenIdByCode")
    public Result getOpenIdByCode(@ApiParam(value = "微信授权code", required = true) @RequestParam String code) {
        AccessTokenOAuth accessTokenOAuth = null;
        try {

            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

            String httpOrgCreateTestRtn = HttpClientUtil.doPost(url, null, "utf-8");

            accessTokenOAuth = JSONObject.parseObject(httpOrgCreateTestRtn, AccessTokenOAuth.class);

        } catch (Exception ex) {
            throw ex;
        }
        if (accessTokenOAuth == null || accessTokenOAuth.getOpenid() ==null) {
            return Result.error("通过code获取openid失败");
        }
        return Result.ok(accessTokenOAuth.getOpenid());
    }


    @ApiOperation(value = "通过openid获取登录用户和token", notes = "通过openid获取登录用户和token")
    @GetMapping("/getUserByOpenid")
    public Result getUserByOpenid(@ApiParam(value = "openId", required = true) @RequestParam String openId) {

//        Map<String, Object> map = new HashMap<>();
//        map.put("open_id", openId);
//        List<SysUser> userDOList = userService.listByMap(map);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getOpenId,openId);
        SysUser sysUser = userService.getOne(queryWrapper);
        if (sysUser != null) {
            Result<JSONObject> result = new Result<JSONObject>();
            result = userService.checkUserIsEffective(sysUser);
            if(!result.isSuccess()) {
                return result;
            }
            JSONObject obj = new JSONObject(new LinkedHashMap<>());
            // 生成token
            String token = JwtUtil.sign(sysUser.getUsername(), sysUser.getPassword());
            // 设置token缓存有效时间
            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 24 / 1000);//pc端24小时
            obj.put("token", token);
            obj.put("userInfo", sysUser);

            return Result.ok(obj);
        }
        return Result.error(MessageFormat.format("未获取到openid={0}用户的token",openId));
    }


    @ApiOperation(value = "小程序通过微信授权code获取用户信息", notes = "如果openid是老用户则直接登录，否则就保存为新用户之后登录")
    @GetMapping("/getUserByCode")
    public Result getUserByCode(@ApiParam(value = "微信授权code", required = true) @RequestParam String code) {
        String time = DateUtils.formatDateTime();
        AccessTokenOAuth accessTokenOAuth = null;
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + secret + "&js_code=" + code + "&grant_type=authorization_code";

            String httpOrgCreateTestRtn = HttpClientUtil.doPost(url, null, "utf-8");

            accessTokenOAuth = JSONObject.parseObject(httpOrgCreateTestRtn, AccessTokenOAuth.class);

        } catch (Exception ex) {
            throw ex;
        }
        if (accessTokenOAuth == null || accessTokenOAuth.getOpenid() ==null) {
            return Result.error("通过code获取openid失败");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("open_id", accessTokenOAuth.getOpenid());
        List<SysUser> userDOList = userService.listByMap(map);
        if (userDOList != null && userDOList.size() > 0) {
            return Result.ok(userDOList.get(0));
        } else {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());
            //user.setUsername(accessTokenOAuth.getOpenid());
            user.setOpenId(accessTokenOAuth.getOpenid());
            //user.setPassword("123qweASD");
            //String salt = oConvertUtils.randomGen(8);
            //String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            //user.setSalt(salt);
            //user.setPassword(passwordEncode);
            user.setStatus(CommonConstant.USER_UNFREEZE);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            userService.save(user);
            if (userService.save(user)) {
                return Result.ok(user);
            }
            return Result.error("保存用户失败");
        }
    }


    /*public static boolean sendTemplateMsg(String token,Template template){
        boolean flag=false;
//        uniform_send
        String requestUrl="https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN";
        requestUrl=requestUrl.replace("ACCESS_TOKEN", token);

        net.sf.json.JSONObject jsonResult= CommonUtil.httpsRequest(requestUrl, "POST", template.toJSON());
        if(jsonResult!=null){
            int errorCode=jsonResult.getInt("errcode");
            String errorMessage=jsonResult.getString("errmsg");
            if(errorCode==0){
                flag=true;
            }else{
                System.out.println("模板消息发送失败:"+errorCode+","+errorMessage);
                flag=false;
            }
        }
        return flag;
    }*/



}

